package aes

import (
	"codeup.aliyun.com/lsxd/zltx/adapter/utils/formater"
	"github.com/dromara/dongle"
)

type Option func(opt *options)

// WithFormat 设置输出格式
func WithFormat(f formater.Formater) Option {
	return func(opt *options) {
		opt.format = f
	}
}

// WithCipher 设置加密器
func WithCipher(c *dongle.Cipher) Option {
	return func(opt *options) {
		opt.cipher = c
	}
}

type options struct {
	format formater.Formater
	cipher *dongle.Cipher
}

type Aes struct {
	o *options
}

// NewAes 创建一个新的Des对象
func NewAes(opts ...Option) *Aes {
	opt := &options{
		format: formater.Base64,
		cipher: dongle.NewCipher(),
	}
	for _, o := range opts {
		o(opt)
	}

	return &Aes{o: opt}
}

// Encrypt 加密数据
func (d *Aes) Encrypt(data string) (string, error) {
	des := dongle.Encrypt.FromString(data).ByAes(d.o.cipher)
	if err := des.Error; err != nil {
		return "", err
	}
	raw := des.ToRawBytes()
	return d.o.format.Encode(raw), nil
}

// Decrypt 解密数据
func (d *Aes) Decrypt(data string) (string, error) {
	content, err := d.o.format.Decode(data)
	if err != nil {
		return "", err
	}
	des := dongle.Decrypt.FromRawBytes(content).ByAes(d.o.cipher)
	if err := des.Error; err != nil {
		return "", err
	}
	return des.ToString(), nil
}
